package com.ants.common.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.ants.common.exception.AntsException;
import com.ants.common.utils.filter.FileTypeFilter;
import com.ants.common.utils.filter.StrAttackFilter;
import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * TODO
 * Author Chen
 * Date   2021/9/7 18:44
 */
@Slf4j
public class MinioUtil {
    private static String minioUrl;
    private static String minioPreviewUrl;
    private static String minioName;
    private static String minioPass;
    private static String bucketName;

    public static void setMinioUrl(String minioUrl) {
        MinioUtil.minioUrl = minioUrl;
    }

    public static void setMinioName(String minioName) {
        MinioUtil.minioName = minioName;
    }

    public static void setMinioPass(String minioPass) {
        MinioUtil.minioPass = minioPass;
    }

    public static void setBucketName(String bucketName) {
        MinioUtil.bucketName = bucketName;
    }

    public static String getMinioUrl() {
        return minioUrl;
    }

    public static String getBucketName() {
        return bucketName;
    }

    public static String getMinioPreviewUrl() {
        return minioPreviewUrl;
    }

    public static void setMinioPreviewUrl(String minioPreviewUrl) {
        MinioUtil.minioPreviewUrl = minioPreviewUrl;
    }

    private static MinioClient minioClient = null;

    /**
     * 上传文件
     *
     * @param file
     * @param uploadpath
     * @return
     */
    @SneakyThrows
    public static JSONObject upload(MultipartFile file, String bizPath, String customBucket, String uploadpath) {
        String file_url = "";
        bizPath = StrAttackFilter.filter(bizPath);
        String newBucket = bucketName;

        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        JSONObject jsonObject = new JSONObject();
        // 图片压缩
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            initMinio(minioUrl, minioName, minioPass);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(newBucket)) {
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(newBucket);
            }
            FileTypeFilter.fileTypeFilter(file);
            // 获取文件名
            String oldName = file.getOriginalFilename();
            if ("".equals(oldName)) {
                oldName = file.getName();
            }
            oldName = CommonUtils.getFileName(oldName);
            String fileName = bizPath + "/"
                    + IdUtil.simpleUUID() + "_" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + oldName.substring(oldName.lastIndexOf(".")
            );
            // 使用putObject上传一个本地文件到存储桶中。
            if (fileName.startsWith("/")) {
                fileName = fileName.substring(1);
            }

            // 拿到文件后缀名，例如：png
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (isPicture(suffix)) {
                // 图片压缩
//                inputStream = ImageUtil.doWithPhoto(inputStream);
                String username = StpUtil.getLoginIdAsString();

                if ("article-details".equals(bizPath)) {
                    inputStream = ImageUtil.watermarkImg(inputStream, "june·12  " + username);
                } else {
                    inputStream = ImageUtil.doWithPhoto(inputStream);
                }

                // 使用putObject上传一个本地文件到存储桶中。
                minioClient.putObject(newBucket, fileName, inputStream, inputStream.available(), "application/octet-stream");
            } else {
                throw new AntsException("请上传图片！");
            }
            file_url = minioPreviewUrl + File.separator + newBucket + File.separator + fileName;
            jsonObject.set("fileName", fileName);
            jsonObject.set("oldFileName", oldName);
            jsonObject.set("url", file_url);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
//                            log.error(e.getMessage(), e);
                }
            }
        }

        return jsonObject;
    }


    /**
     * 文件上传
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static JSONObject upload(MultipartFile file, String bizPath) {

        return upload(file, bizPath, null, null);
    }

    /**
     * 文件上传
     *
     * @param inputStream
     * @param customBucket
     * @return
     */
    public static String wxCodeUpload(InputStream inputStream, String customBucket, String id) {
        String url = "";
        String newBucket = bucketName;
        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        try {
            initMinio(minioUrl, minioName, minioPass);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(newBucket)) {
                log.info("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(newBucket);
                log.info("create a new bucket.");
            }

            String fileName = "wxCode" + "/" + id + ".png";
            // 使用putObject上传一个本地文件到存储桶中。
            if (fileName.startsWith("/")) {
                fileName = fileName.substring(1);
            }

            // 使用putObject上传一个本地文件到存储桶中。
            minioClient.putObject(newBucket, fileName, inputStream, inputStream.available(), "application/octet-stream");


            inputStream.close();
            url = minioUrl + newBucket + "/" + fileName;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return url;
    }

    /**
     * 文件上传
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static JSONObject upload(MultipartFile file, String bizPath, String customBucket) {

        return upload(file, bizPath, customBucket, null);
    }

    /**
     * 获取文件流
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public static InputStream getMinioFile(String bucketName, String objectName) {
        InputStream inputStream = null;
        try {
            initMinio(minioUrl, minioName, minioPass);
            inputStream = minioClient.getObject(bucketName, objectName);
        } catch (Exception e) {
            log.info("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param objectName
     * @throws Exception
     */
    public static boolean removeObject(String bucketName, String objectName) {
        try {
            initMinio(minioUrl, minioName, minioPass);
            minioClient.removeObject(bucketName, objectName);
        } catch (Exception e) {
            log.info("文件删除失败" + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 获取文件外链
     *
     * @param bucketName
     * @param objectName
     * @param expires
     * @return
     */
    public static String getObjectURL(String bucketName, String objectName, Integer expires) {
        initMinio(minioUrl, minioName, minioPass);
        try {
            String url = minioClient.presignedGetObject(bucketName, objectName, expires);
            return URLDecoder.decode(url, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param bucketName 存储桶
     * @param objectName 文件名
     * @return
     */
    public static boolean isObjectExist(String bucketName, String objectName) {
        boolean exist = true;
        try {
            minioClient.statObject(bucketName, objectName);
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }


    /**
     * 初始化客户端
     *
     * @param minioUrl
     * @param minioName
     * @param minioPass
     * @return
     */
    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        if (minioClient == null) {
            try {
                minioClient = new MinioClient(minioUrl, minioName, minioPass);
            } catch (InvalidEndpointException e) {
                e.printStackTrace();
            } catch (InvalidPortException e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }

    /**
     * 上传文件到minio
     *
     * @param stream
     * @param relativePath
     * @return
     */
    @SneakyThrows
    public static String upload(InputStream stream, String relativePath) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException, InvalidArgumentException {
        initMinio(minioUrl, minioName, minioPass);
        if (minioClient.bucketExists(bucketName)) {
            log.info("Bucket already exists.");
        } else {
            // 创建一个名为ota的存储桶
            minioClient.makeBucket(bucketName);
            log.info("create a new bucket.");
        }
        minioClient.putObject(bucketName, relativePath, stream, stream.available(), "application/octet-stream");
        stream.close();
        return minioUrl + bucketName + "/" + relativePath;
    }

    /**
     * 判断文件是否为图片
     */
    public static boolean isPicture(String imgName) {
        boolean flag = false;
        if (StringUtils.isBlank(imgName)) {
            return false;
        }
        String[] arr = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
        for (String item : arr) {
            if (item.equals(imgName)) {
                flag = true;
                break;
            }
        }
        return flag;
    }


    public static void main(String[] args) {
        File file = new File("C:\\Users\\LX\\Pictures\\微信图片_20200717161454.jpg");
        if (!file.exists()) {
            return;
        }
        BufferedImage image = null;
        FileOutputStream os = null;
        try {
            image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            os = new FileOutputStream("D:\\微信图片_20200717161454.jpg");
            ImageIO.write(bfImage, "jpg", os);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//            encoder.encode(bfImage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
